package com.skp.shaphan.menus;

import java.awt.Component;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;

import javax.swing.JMenuItem;
import javax.swing.KeyStroke;

import com.skp.shaphan.ShaphanApp;
import com.skp.shaphan.ui.DatabasePathSelector;
import com.skp.shaphan.ui.buttons.ButtonsPane;
import com.skp.shaphan.ui.buttons.ConnectionOKButton;
import com.skp.shaphan.ui.dialogs.ConnectionDialog;

/**
 * Connects to a database and load SQL in the editor for testing
 * @author skp
 *
 */
public class DevSQLTestMenuItem extends JMenuItem implements ActionListener {
	/**
	 * 
	 */
	private static final long serialVersionUID = 7912302846574513812L;

	public DevSQLTestMenuItem() {
		super("Test SQL");
		this.setMnemonic('S');
		this.setAccelerator(KeyStroke.getKeyStroke('T', InputEvent.CTRL_DOWN_MASK));
		this.addActionListener(this);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		ConnectionConnectMenuItem connectMenu = new ConnectionConnectMenuItem(ConnectionConnectMenuItem.SWING_DIALOG_TYPE);
		connectMenu.doClick();
		Window[] windows = ShaphanApp.getMainWindow().getOwnedWindows();
		ConnectionDialog dialog = null;
		for(Window window : windows) {
			if(window instanceof ConnectionDialog) {
				dialog = (ConnectionDialog)window;
				break;
			}
		}
		if(dialog == null) {
			System.err.println("ConnectionDialog not found!");
		}
		DatabasePathSelector path = null;
		ButtonsPane buttons = null;
		for(Component c : dialog.getContentPane().getComponents()) {
			if(c instanceof DatabasePathSelector) {
				path = (DatabasePathSelector)c;
			} else if(c instanceof ButtonsPane) {
				buttons = (ButtonsPane)c;
			}
		}
		if(path == null) {
			System.err.println("Database path not found");
		}
		if(buttons == null) {
			System.err.println("buttons not found");
		}
		path.setPath("/home/skp/Desktop/Landmark/Landmark");
		ConnectionOKButton okButton = null;
		for(Component c : buttons.getComponents()) {
			if(c instanceof ConnectionOKButton) {
				okButton = (ConnectionOKButton)c;
			}
		}
		if(okButton == null) {
			System.err.println("OK button not found");
		}
		okButton.doClick();
		ShaphanApp.getMainWindow().getSqlEditor().setSQL("select * from tblMember");
	}
}
